#include "virDir.h"
#include <myHeader.h>
#include <string.h>

/* Usage:  */



int initStack(Stack_t *pStack){
    memset(pStack,0,sizeof(Stack_t));
    StackNode_t *pSentiel=(StackNode_t *)calloc(1,sizeof(StackNode_t));
    pStack->pFront=pSentiel;
    pStack->pRear=pSentiel;

    // 这里应该加上：
    pSentiel->pNext = NULL;      // 哨兵的下一节点为空
    pSentiel->pPrevious = NULL;  // 哨兵的前驱为空

    return 0;
}  

int isStackEmpty(Stack_t *pStack){
    return (pStack->stackSize==0);
}
int pushStack(Stack_t *pStack,char *pathSegment){
    StackNode_t *pNewNode=(StackNode_t *)calloc(1,sizeof(StackNode_t));
    ERROR_CHECK(pNewNode,NULL,"stack new node");
    strcpy(pNewNode->pathSegment,pathSegment);
    pNewNode->pNext=pStack->pFront->pNext;
    pNewNode->pPrevious=pStack->pFront;
    if(!isStackEmpty(pStack)){
        pStack->pFront->pNext->pPrevious=pNewNode;
    }
    else{
        pStack->pRear=pNewNode;
    }
    pStack->pFront->pNext=pNewNode;
    ++pStack->stackSize;
    return 0;
}

char * popStack(Stack_t *pStack){
    if(isStackEmpty(pStack)){
        return 0;
    }
    StackNode_t *pTmp=pStack->pFront->pNext;
    if(pStack->stackSize==1){
        pStack->pRear=pStack->pFront;
    }
    else{
       pTmp->pNext->pPrevious=pStack->pFront;
       pStack->pFront->pNext=pTmp->pNext;
    }
    char *pOld=(char *)malloc(64*sizeof(char));
    strcpy(pOld,pTmp->pathSegment);
    free(pTmp);
    --pStack->stackSize;
    return pOld;
}

int sPrintfStack(Stack_t *pStack, char *path){
    StackNode_t *pTmp = pStack->pRear;
    char *cur = path;
    *cur = '\0';  // 清空path字符串
    while (pTmp != pStack->pFront) {  // 遍历到哨兵节点结束
        *cur++ = '/';                 // 先添加路径分隔符 '/'
        size_t len = strlen(pTmp->pathSegment);
        strcpy(cur, pTmp->pathSegment); // 拷贝当前路径段
        cur += len;
        pTmp = pTmp->pPrevious;
    }
    *cur = '\0';  // 字符串结束符

    return 0;
}
int copyStack(Stack_t *pSrc, Stack_t *pDst) {
    initStack(pDst); // 初始化目标栈

    // 为了保持顺序，从栈顶向下遍历，用数组记录顺序
    char *segments[1024];
    int count = 0;

    StackNode_t *pNode = pSrc->pRear;  // ✅ 从栈顶开始
    while (pNode != pSrc->pFront && count < 1024) {
        segments[count++] = pNode->pathSegment;
        pNode = pNode->pPrevious;
    }

    // 然后从头到尾 push，保持顺序一致
    for (int i = 0; i < count; ++i) {
        pushStack(pDst, segments[i]);
    }

    return 0;
}
